# -*- coding: utf-8 -*-

'''
/**
 * @file        az_jlink.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2024/08/08
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2024/08/08   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os
import argparse
import time

import pylink

from datetime import datetime
# 获取当前日期
CURR_DATE_STRING = datetime.now().strftime("%Y-%m-%d")
# 获取当前时间
CURR_TIME_STRING = datetime.now().strftime("%H:%M:%S")
## 获取当前脚本所在的目录
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# 输出目录路径
# print("SCRIPT_DIR: "+ SCRIPT_DIR)






# g_az_jlink = pylink.JLink()

# def open_jlink() -> pylink.JLink:
#     # global g_az_jlink
#     g_az_jlink.open()
#     if g_az_jlink.opened() == False:
#         raise Exception("Failed to open J-Link.")
#     print(f"J-Link opened. product_name:{g_az_jlink.product_name}")
#     return g_az_jlink

# def close_jlink():
#     global g_az_jlink
#     g_az_jlink.close()

# def connect_to_device(device='Cortex-M4', speed_khz=4000):
#     if g_az_jlink.connected() == False:
#         g_az_jlink.connect(chip_name=device, speed=speed_khz, verbose=False)
#         print(f"Connected to device:{device}, speed:{speed_khz}kHz")
#     else:
#         print("Device already connected.")
#     return g_az_jlink.connected()


# def reset_device():
#     global g_az_jlink
#     g_az_jlink.reset(ms=0, halt=True)

# def is_connected():
#     global g_az_jlink
#     return g_az_jlink.connected()



# ================================================================================
import telnetlib

class TTelnetRtt:
    HOST='127.0.0.1'
    PORT=19021
    init_cnt = 0

    _rtt_instance = telnetlib.Telnet()

    def recv_data_callback(line:str):
        print(f"[TTelnetRtt.recv_data_callback] >> {line}")
        return

    def __init__(self):
        self._rtt_instance.open(self.HOST, self.PORT)
        temp = self._rtt_instance.read_until(b'.exe\r\n')
        self._received_lines = list()
        self._received_lines.append(temp.decode('ascii'))
        self._arrival_callback = None

    def set_callback(self, func: recv_data_callback):
        self._arrival_callback = func

    def start_daemon(self):
        import threading
        def receive_loop():
            while True:
                try:
                    line = self._rtt_instance.read_until(b'\n')
                    if self._arrival_callback:
                        self._arrival_callback(line.decode('ascii', 'ignore'))
                    else:
                        print(line.decode('ascii', 'ignore'))

                except EOFError as err:
                    print(err)
                    self.__init__()
                except Exception:
                    print('error while read')
        self._recv_thread = threading.Thread(target = receive_loop, args = ())
        self._recv_thread.setDaemon(True)
        self._recv_thread.start()

    def readline(self):
        
        line = ""
        if len(self._received_lines) > 0:
            line = self._received_lines[0]
            self._received_lines.pop(0)
        return line

    def writeline(self, line):
        self._rtt_instance.write((line+'\n').encode('ascii'))

    def __del__(self):
        # we close the telnet connection, so that the daemon thread will crash.
        print("close rtt")
        self._rtt_instance.close()


if __name__ == "__main__":

    rtt = TTelnetRtt()
    rtt.start_daemon()
    while True:
        line = rtt.readline()
        if line != "":
            print(line)
        else:
            time.sleep(0.1)




    ## 获取脚本传参
    argv = sys.argv
    argc = len(argv)
    # 打印命令行参数
    #for i in range(1, argc):
        #print("参数", i, ":", argv[i])


    # 设置命令行参数解析器
    # parser = argparse.ArgumentParser(description='Filter log file based on keywords.')
    # parser.add_argument('input_file', type=str, help='Input log file path')
    # parser.add_argument('output_file', type=str, help='Output filtered log file path')
    # parser.add_argument('filter_list', nargs='+', type=str, help='List of keywords to filter')

    # 解析命令行参数
    # args = parser.parse_args()

        
    print("============= BIGEN: az_jlink.py =============")

    # 打开 J-Link 连接
    open_jlink()
    print("Connected to J-Link.")

    # 连接到目标设备
    connect_to_device(device='Cortex-M4', speed_khz=4000)
    print("Connected to device. result:", is_connected())


    # 复位设备
    reset_device()
    print("Device has been reset.")

    # 这里可以添加更多的操作，例如内存读写等
    print("Connected to device. result:", is_connected())


    # finally:
    #     # 关闭 J-Link 连接
    #     print("J-Link connection closed.")

    print("============= END: az_jlink.py =============")



## Generated on "2024-08-08 19:52:21" by the tool "gen_hq_file.py >> V20231119" 

